﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bzzb.Model;
using FreeSql;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Bzzb.Controllers
{
    public class AdminController : BaseController
    {
        private readonly ILogger<AdminController> _logger;
        public AdminController(ILogger<AdminController> logger, IFreeSql fsql) : base(fsql)
        {
            this._logger = logger;
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Index([FromForm] int doPage = 1, [FromForm] int pageNumber = 1, [FromForm] int pageSize = 10)
        {
            ISelect<User> iselect = _fsql.Select<User>().Where(u => u.Id > 1).OrderBy("id desc");
            List<User> users;
            long total = -1;
            if (doPage == 0)
            {
                users = await iselect.ToListAsync();
            }
            else
            {
                users = await iselect.Count(out total).Page(pageNumber, pageSize).ToListAsync();
            }
            JObject data = new();
            data.Add("total", total);
            data.Add("data", users == null ? null : JArray.FromObject(users));
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] User user)
        {
            User insertUser = await _fsql.Select<User>().Where(u => u.Username == user.Username).ToOneAsync();
            if (insertUser != null)
            {
                return RenderJson(status: "failed", message: "该账户已经存在", code: 1001, data: user);
            }
            int affrows = await _fsql.Insert(user).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id) {
            User user = await _fsql.Select<User>().Where(u => u.Id == id).ToOneAsync();
            if (user.Id == 1) {
                return RenderJson(status: "failed", message: "管理员无法删除", code: -1, data: user);
            }
            int affrows = await _fsql.Delete<User>().Where(u => u.Id == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] User user) {
            int affrows = await _fsql.Update<User>().SetSource(user).ExecuteAffrowsAsync();

            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Show([FromForm] long id) {
            User user = await _fsql.Select<User>().Where(u => u.Id == id).ToOneAsync();

            return RenderJson(data: user);
        }
    }
}
